package com.kaisu.blog.web.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaisu.blog.web.result.Result;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * @author kaisu
 */
@RestControllerAdvice(basePackages = "com.kaisu.blog.web")
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    public ResponseAdvice(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean supports(@NonNull MethodParameter returnType, @NonNull Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body,
                                  @NonNull MethodParameter returnType,
                                  @NonNull MediaType selectedContentType,
                                  @NonNull Class selectedConverterType,
                                  @NonNull ServerHttpRequest request,
                                  @NonNull ServerHttpResponse response) {
        // 如果Controller直接返回String的话，SpringBoot是直接返回，故我们需要手动转换成json。
        if (body instanceof String) {
            return objectMapper.writeValueAsString(Result.success(body));
        }
        // 如果返回的结果是ResultData对象，直接返回即可。
        if (body instanceof Result) {
            return body;
        }
        // 如果body为空
        if (Objects.isNull(body)) {
            return Result.success(objectMapper.createObjectNode());
        }
        return Result.success(body);
    }
}